package com.tt.socket;

import com.tt.thread.TailLogThread;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * lenovo
 * 2022/3/6 - 18:25
 */
public class TtWebSocketHandler implements WebSocketHandler
{
    //保存用户链接
    private static ConcurrentHashMap<String, WebSocketSession> users = new ConcurrentHashMap<>();

    private Process process;

    private InputStream inputStream;

    /**
     * 连接 就绪时
     * @param webSocketSession
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception
    {
        try {
            // 执行tail -f命令
            process = Runtime.getRuntime().exec("tail -f F:\\SpringMVP\\tt-shop\\shop-system\\logs\\tt-shop-system.log");
            inputStream = process.getInputStream();

            // 一定要启动新的线程，防止InputStream阻塞处理WebSocket的线程
            TailLogThread tailLogThread = new TailLogThread(inputStream, webSocketSession);
            Thread thread = new Thread(tailLogThread);
            thread.start();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    // 处理信息
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception
    {
        Object payload = webSocketMessage.getPayload();
        System.out.println(payload.toString());
    }

    // 处理传输时异常
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception
    {

    }

    // // 用户退出后的处理，不如退出之后，要将用户信息从websocket的session中remove掉，这样用户就处于离线状态了，也不会占用系统资源
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception
    {
        try
        {
            if(inputStream != null){
                inputStream.close();
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        if(process != null){
            process.destroy();
        }

    }

    //是否支持分包
    @Override
    public boolean supportsPartialMessages()
    {
        return false;
    }

    /**
     * 发送消息给指定的用户
     */
    public void sendMessageToUser(String sessionId, TextMessage message) {
        WebSocketSession user = users.get(sessionId);
        try {
            if (user.isOpen()) {
                user.sendMessage(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 给所有的用户（包括自己）发送消息
     */
    public void sendMessagesToUsers(TextMessage message) {

        Iterator<WebSocketSession> userIt = users.values().iterator();
        while (userIt.hasNext()){
            WebSocketSession user = userIt.next();
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给所有的用户（除了自己）发送消息
     */
    public void sendMessagesToUsers(TextMessage message, String sessonId) {

        for (Map.Entry<String, WebSocketSession> entry : users.entrySet()) {
            String key = entry.getKey();
            if (!key.equals(sessonId)){
                WebSocketSession user = entry.getValue();
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
